//
//  ImageGridViewController.swift
//  GifUsage
//
//  Created by han on 2020/12/29.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos

class ImageGridViewController: UIViewController {
    
    var dataSource = [UIImage]()
    
    var gifAsset: PHAsset?
    var gifName: String?
    
    var column: CGFloat = 3
    let padding: CGFloat = 1
    
    var selectedIndices = [Int]()
    
    var isEditImage: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    let activityIndicator = UIActivityIndicatorView(style: .large)
   
    var saveItem: UIBarButtonItem!
    var choseItem: UIBarButtonItem!
    var cancleItem: UIBarButtonItem!
   
   
    lazy var flowLayout: UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = padding
        flowLayout.minimumInteritemSpacing = padding
        flowLayout.scrollDirection = .vertical
        return flowLayout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = .black
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
    }()
}

// MARK: Private
extension ImageGridViewController {
    private func commonInit() {
        setupNavigationBar()
        setupSubviews()
        loadDataSource()
        loadGifDataSource()
    }
    
    private func setupNavigationBar() {
        navigationItem.title = "Images"
        view.backgroundColor = .black
         saveItem = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAllAction))
         choseItem = UIBarButtonItem(title: "选择", style: .done, target: self, action: #selector(editAction))
         cancleItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(cancleAction))
        choseItem.title = "选择"
        navigationItem.rightBarButtonItems = [saveItem, choseItem]
    }
    
    @objc func editAction() {
        if isEditImage { // 选择状态，点击，进入全选功能
            selectedIndices.removeAll()
            selectedIndices.append(contentsOf: 0 ..< dataSource.count)
        } else { // 进入选择状态
            isEditImage = true
            choseItem.title = "全选"
            navigationItem.rightBarButtonItems = [saveItem, choseItem, cancleItem ]
        }
        collectionView.reloadData()
    }
    
    @objc func cancleAction() { // 点击取消，进入非选择状态
        if isEditImage { // 非选择状态
            isEditImage = false
            selectedIndices.removeAll()
            choseItem.title = "选择"
            navigationItem.rightBarButtonItems = [saveItem, choseItem]
            collectionView.reloadData()
        }
    }
    
    @objc func saveAllAction() {
        guard selectedIndices.count > 0 else { return }
        activityIndicator.startAnimating()
        
        PHPhotoLibrary.shared().performChanges({
            self.selectedIndices.map {
                self.dataSource[$0]
            }.forEach {
                PHAssetChangeRequest.creationRequestForAsset(from: $0)
            }
        }, completionHandler: {success, error in
            if !success { print("error creating asset: \(String(describing: error))") }
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                showTips(self, success ? "保存成功" : "保存失败", success ? "" : "error creating asset: \(String(describing: error))")
            }
        })
    }
    
    private func setupSubviews() {
        view.addSubview(collectionView)
        collectionView.register(ImageGridCell.self, forCellWithReuseIdentifier: String(describing: ImageGridCell.self))
        collectionView.frame = view.bounds
        let itemWidth = self.itemWidth
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        view.addSubview(activityIndicator)
        activityIndicator.center = CGPoint(x: view.frame.midX, y: view.frame.midY)
        activityIndicator.color = .white
    }
    
    private func loadDataSource() {
        guard let asset = gifAsset else { return }
        guard let gifResource = asset.gifResource  else { return }
        
        activityIndicator.startAnimating()
        
        let resourceOption = PHAssetResourceRequestOptions()
        resourceOption.isNetworkAccessAllowed = true
        
        var gifData = Data()
        PHAssetResourceManager.default().requestData(for: gifResource, options: resourceOption) { (data) in
            gifData.append(data)
        } completionHandler: { (error) in
            self.dataSource = GIFTools.gifImages(withGIFData: gifData)
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                self.collectionView.reloadData()
            }
        }
    }
    
    private func loadGifDataSource() {
        guard let name = gifName else {  return }
        activityIndicator.startAnimating()
        DispatchQueue.global().async {
            self.dataSource = GIFTools.gifImages(withGIFNamed: name)
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                self.collectionView.reloadData()
            }
        }
    }
    
    private var itemWidth: CGFloat  {
        let scale = UIScreen.main.scale
        let width = floor(scale * (view.bounds.width - padding * (column - 1)) / column) / scale
        return width
    }
    
    func scrollToPosition(to position: Int) {
        let indexPath = IndexPath(item: position, section: 0)
        if collectionView.indexPathsForVisibleItems.contains(indexPath) {
            return
        }
        collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
    }
}

// MARK: UICollectionViewDelegate
extension ImageGridViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int { 1 }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: ImageGridCell.self), for: indexPath) as! ImageGridCell
        cell.thumbnailImage = dataSource[indexPath.row]
        cell.isEditing = isEditImage
        cell.isMarked = selectedIndices.contains(indexPath.row)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        if isEditImage {
            if selectedIndices.contains(indexPath.row) {
                selectedIndices.remove(at: selectedIndices.firstIndex(of: indexPath.row)!)
            } else {
                selectedIndices.append(indexPath.row)
            }
            collectionView.reloadItems(at: [indexPath])
        } else {
            let imageVC = ImageViewController()
            imageVC.image = dataSource[indexPath.row]
            navigationController?.pushViewController(imageVC, animated: true)
        }
       
    }
}





